package com.cx.proxy.demo;

import com.sun.org.apache.bcel.internal.generic.NEW;
import net.sf.cglib.proxy.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package com.cx.proxy.demo
 * @Description:
 * @Date 2025/5/28 16:19
 */

public class ImageTest {
    //2、创建一个图片加载系统，使用代理模式来控制对真实图片加载和下载。
    //需求：
    //添加访问控制，检查用户是否有权限查看和下载图片。
    //如果用户的权限列表中存在加载图片或下载的图片的权限（方法名同），就能加载或下
    //载图片，否则抛出异常。
}

interface Image {
    //显示图片
    void display();
    //下载图片
    void download();

    void save();
}
class User {
   private ArrayList<String> roles = new ArrayList<>();
   //授权
   public void grantPermission(String role){
       roles.add(role);}





    // 回收权限
    public void revokePermission(String role) {
        roles.remove(role);
    }
    // 检查权限
    public boolean hasPermission(String role) {
        return roles.contains(role);
    }
    public ArrayList<String> getRoles() {
        return roles;
    }





}

class RealImage implements Image {
    private String name;
    public RealImage(String name) {
        this.name = name;

    }

    public RealImage() {
    }

    @Override
    public void display() {
        System.out.println("Displaying " + name);
    }
    @Override
    public void download() {
        System.out.println("Downloading " + name);
    }

    @Override
    public void save() {
        System.out.println("save " + name);
    }
}
class ProxyImage implements InvocationHandler {
    private Object target;
    private User user;

    public ProxyImage(Object target,User user) {
        this.target = target;
        this.user = user;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String name = method.getName();
        if(user.getRoles().contains(name)){
            return method.invoke(target,args);
        }else {
            if("display".equals(name)){
                System.out.println("你没有权限查看图片");
            }else if("download".equals(name)){
                System.out.println("你没有权限下载图片");
            }
        }
        return null;
    }
    public Object getProxy(){
        //创建一个代理对象
        Object proxy = Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
        return proxy;
    }

    public static void main(String[] args) {
        Image realImage = new RealImage("梦娜丽莎.jpg");
        User user = new User();
        user.grantPermission("display");

        Image proxy = (Image) new ProxyImage(realImage,user).getProxy();
        proxy.display();
        proxy.download();
        proxy.save();
    }
}
